<?php 

namespace IMT\ServicesBundle\Controller;

use JMS\Serializer\SerializationContext;

use IMT\ContactBundle\Entity\Contact;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
use FOS\Rest\Util\Codes;

class ContactRestController extends Controller
{
	/**
	 * GET /contact/{eventId}
	 *
	 * @param string $eventId
	 * @return Response
	 */
	public function getContactAction($contactId)
	{			
		if(intval($contactId) == 0)
	    	throw new \InvalidArgumentException(400, 'L\'id est incorrect : '.$contactId);
	    
    	// Récupération de l'contact
    	$repository = $this->getDoctrine()->getRepository('IMTUserBundle:Contact');
   		$contact = $repository->findOneById($contactId);
   		
   		if (!$contact)
   			throw new NotFoundHttpException('Le contact ayant l\'id '.$contactId.' n\'existe pas');
   		
   		
   		// Vérification des droits d'acces
   		$securityContext = $this->get('security.context');   		
   		
   		$context = new SerializationContext();
   		$context->setVersion('1.0');
   		$context->setGroups(array('contact_details', 'event_list', 'group_list', 'account_list'));
   			   		
		$view = View::create()
			->setStatusCode(200)
			->setData($contact)
			->setSerializationContext($context);

		return $this->get('fos_rest.view_handler')->handle($view);
	}
	
	/**
	 * Creates a new Thread from the submitted data.
	 *
	 * @param Request $request The current request
	 *
	 * @return View
	 */
	public function postContactAction(Request $request)
	{
		$idContact = 0;
	
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		if('POST' == $request->getMethod()){
			$idContact = $request->request->get('contact_id');
			
			$validator = $this->get('validator');
			
			$contact = null;
						
			$user = $this->get('security.context')->getToken()->getUser();
	
			if($idContact == 0){
				$contact = new Contact();
			} else {
				$contact = $em->getRepository('IMTUserBundle:Contact')->find($idContact);
					
				if(!$contact)
					throw $this->createNotFoundException('Le contact "'.$idContact.'" n\'existe pas');
			}
			
			$contact->setFirstname($request->request->get('contact_firstname'));
			$contact->setName($request->request->get('contact_name'));
			$contact->setEmail($request->request->get('contact_email'));
			
			$idUser = intval($request->request->get('contact_user'));
			
			if($idUser){
				$user = $em->getRepository('IMTUserBundle:User')->find($idUser);
				
				if($user){
					$contact->setUser($user);
				}
			}
			
			$accounts = $request->request->get('contact_email');
			if($accounts && is_array($accounts)){
				foreach($accounts as $accountId){
					$account = $em->getRepository('IMTAccountBundle:Account')->find($accountId);
					
					if($account)
						$contact->addAccount($account);
				}
			}
						
			//return $viewHandler->handle($this->createErrorViewResponse($contact));
			$errors = $validator->validate($contact);
			
			if(count($errors) > 0){
				$return['errors'] = $errors;
			
				return $viewHandler->handle($this->createErrorViewResponse($return));
			} else {
				$em = $this->getDoctrine()->getEntityManager();
				$em->persist($contact);
				$em->flush();
					
				$return['idContact'] = $contact->getId();
			
				return $viewHandler->handle($this->createSuccessViewResponse($return));
			}
		} else {
			throw new MethodNotAllowedException('POST');
		}
	
	}
	
	public function deleteContactAction($id)
	{
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		$entity = $em->getRepository('IMTUserBundle:Contact')->find($id);
		
		$user = $this->get('security.context')->getToken()->getUser();
		
		if (!$entity) {
			throw $this->createNotFoundException('Le contact "'.$id.'" n\'existe pas');
		} 
		
		$em->remove($entity);
		$em->flush();
		
		return $viewHandler->handle($this->createSuccessViewResponse(array('idContact' => $id)));
	}
	
	private function createSuccessViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(200)
		->setData($return);
	
		return $view;
	}
	
	private function createErrorViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(Codes::HTTP_BAD_REQUEST)
		->setData($return);
	
		return $view;
	}
}